package net.xin.dao.impl;


import java.util.List;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Component;

import net.xin.dao.UserDAO;
import net.xin.model.User;

@Component(value="sqlDAO")	/*相当于在xml中初始化对象*/
@Scope(value="singleton")
public class UserDAOMySqlImpl implements UserDAO {
	
	HibernateTemplate hibernateTemplate;
	
	@Resource	//装配
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	@Override
	public void save(User user) {
		/*以前的方法*/
//		Session session=HibernateUtil.openSession();
//		session.beginTransaction();
//		session.merge(user);
//		session.getTransaction().commit();
//		session.close();
		
		/*使用HibernateTemplate的方法*/
		hibernateTemplate.merge(user);	/*要注入到applicationContext.xml中*/
		
	}

	@Override
	public boolean isExists(User user) {
		// TODO Auto-generated method stub
		return hibernateTemplate.findByExample(user).size()>0;
	}

	@Override
	public User get(User user) {
		// TODO Auto-generated method stub
		List<User> list=hibernateTemplate.findByExample(user);
		if(list.size()>0) {
			System.out.println("list.size:"+list.get(0));
			return list.get(0);
		}
		return null;
	}

	
}
